package com.acme.bankapp.domain.bank;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class QueueImpl implements Queue {
	
	private Lock lock = new ReentrantLock();
	private Condition notEmpty = lock.newCondition();
	private List<Email> mails = new ArrayList<Email>();
	
	public void addEmail(Email email) {
		lock.lock();
		this.mails.add(email);	
		notEmpty.signal();
		lock.unlock();
	}

	public Email getEmail() {
		lock.lock();
		while(mails.isEmpty()) {
			try {
				notEmpty.await();
			} catch (InterruptedException e) {}
		}
		try {
			return this.mails.remove(0);
		} finally {
			lock.unlock();
		}
	}
	
	public boolean isEmpty() {
		return this.mails.isEmpty();
	}
	
}